/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-02-29
 * Time: 17:47
 */
public class HashBuck {
    static class Node {
        public int key;
        public int val;
        public Node next;

        public Node(int key,int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] array;
    public int usedSize;

    //负载因子
    public static final double LOAD_FACTOR = 0.75;

    public HashBuck() {
        array = new Node[8];
    }

    public void put(int key,int val) {
        int index = key % array.length;
        Node cur = array[index];

        while(cur != null) {
            //替换操作，不能有重复的
            if(cur.key == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }

        Node node = new Node(key,val);
        node.next = array[index];
        array[index] = node;
        usedSize++;

        if(calculateLoadFactor() >= LOAD_FACTOR) {
            resize();
        }
    }

    private void resize() {
        Node[] newArray = new Node[2*array.length];
        //一定要注意核心代码 重新映射放置
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null) {
                Node curNext = cur.next;
                int index = cur.key % newArray.length;
                cur.next = newArray[index];
                newArray[index] = cur;
                cur = curNext;
            }
        }
        array = newArray;
    }

    //计算负载因子
    private double calculateLoadFactor() {
        return usedSize*1.0/ array.length;
    }

    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while(cur != null) {
            if(cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }





































}
